import React from 'react';
import styled from 'styled-components';

/** 此时外层ref拿到的就是这个input标签元素*/
const Input = styled.input`
  padding: 0.5em;
  margin: 0.5em;
  color: palevioletred;
  background: papayawhip;
  border: none;
  border-radius: 3px;
`;

/** 此时外层ref拿到的是这个类的实例
 * ，无法修改ref指向*/
/*const _ComponentInput = class X extends React.Component{
  render(){
    const {placeholder, onMouseEnter, className} = this.props;
    console.log('this.props:', this.props);
    return <input type="text" onMouseEnter={this.props.onMouseEnter} placeholder={placeholder} className={className} />;
    /!**
     * 这样我们在外面拿到的this.componentInputRef是 class X
     * *!/
  }
};*/

/** 此时外层ref拿到的是我们在这个函数组件里手动指向的某个元素
 * ,可以手动指定ref指向*/
const _ComponentInput = React.forwardRef((props,ref/*←这个就是函数组件接受到的ref*/) => {
  console.log('props:', props);
  console.log('ref:', ref);
  return <input type="text" ref={ref} {...props}/>
});

const ComponentInput = styled(_ComponentInput)`
  padding: 0.5em;
  margin: 0.5em;
  color: palevioletred;
  background: papayawhip;
  border: none;
  border-radius: 3px;
`;

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.componentInputRef = React.createRef();
  }

  render() {
    return (
      <>
        <Input
          ref={this.inputRef}
          placeholder="Hover to focus!"
          onMouseEnter={() => {
            console.log('this.inputRef:', this.inputRef);
            this.inputRef.current.focus()
          }}
        />
        <ComponentInput
          ref={this.componentInputRef}
          placeholder="Hover to focus!"
          onMouseEnter={() => {
            console.log('this.componentInputRef:', this.componentInputRef);

            /** 如果styled()是一个类组件 那么这个ref是该类组件的实例*/
            // console.log(this.componentInputRef.current instanceof _ComponentInput); // true

            /** 如果styled()是一个函数组件 那么这个ref是我们通过React.forwardRef接受到然后设置给的那个东东*/
            this.componentInputRef.current.value = 'test';
          }}
        />
      </>
    );
  }
}

export default Form;
